package com.fivetalks.client;



import java.io.UnsupportedEncodingException;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.fivetalks.network.Definition;

public class JoinFormActivity extends Activity implements OnClickListener, 
OnCheckedChangeListener{
	
	ImageButton btSubmit;
	ImageButton btCancel;
	EditText etEmail;
	EditText etPassword;
	EditText etNickname;
	EditText etAge;
	RadioGroup rgGender;
	String email;
	String password;
	String nickname;
	String age;
	String gender;
//	final String MALE = "0";
//	final String FEMALE = "1";
	private final String URL =  Definition.URL_ROOT + "/member/join";
//	private final String URL =  "http://10.201.208.180:8080/myproject/test";
//	private final String URL =  "http://192.168.0.27:8080/myproject/member/join";
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_form);
        
        etEmail = (EditText)findViewById(R.id.etEmail);
        etPassword = (EditText)findViewById(R.id.etPassword);
        etNickname = (EditText)findViewById(R.id.etNickname);
        etAge = (EditText)findViewById(R.id.etAge);
        rgGender = (RadioGroup)findViewById(R.id.rgGender);
        rgGender.setOnCheckedChangeListener(this);
        
        btSubmit = (ImageButton) findViewById(R.id.btSubmit);
        btSubmit.setOnClickListener(this);
        
        btCancel = (ImageButton) findViewById(R.id.btCancel);
        btCancel.setOnClickListener(this);
        
        gender="남자";
        
    }
    
    @Override
	public void onClick(View v){
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btSubmit:
			email= etEmail.getText().toString();
			password= etPassword.getText().toString();
			nickname= etNickname.getText().toString();
			age = etAge.getText().toString();
			if(email.isEmpty() || email.contains(" "))
			{
				Toast.makeText(this, R.string.join_form_error_email, Toast.LENGTH_SHORT).show();
				break;
			}
			else if(password.contains(" ") || password.length() < 4)
			{
				Toast.makeText(this, R.string.join_form_error_password, Toast.LENGTH_SHORT).show();
				break;
			}
			else if(nickname.isEmpty() || nickname.contains(" "))
			{
				Toast.makeText(this, R.string.join_form_error_nickname, Toast.LENGTH_SHORT).show();
				break;
			}
			else if(age.isEmpty() || age.contains(" "))
			{
				Toast.makeText(this, R.string.join_form_error_age, Toast.LENGTH_SHORT).show();
				break;
			}
			else
			{ 	
				GetAsyncTask gat = new GetAsyncTask();
				gat.execute(URL);
//				Thread thread=new DataSender(nameValue);
//				thread.start();
			}
		break;
		case R.id.btCancel:
			etEmail.setText("");
			etPassword.setText("");
			etNickname.setText("");
			etAge.setText("");
		break;
		}
	}
    
    @Override
    public void onCheckedChanged(RadioGroup group,int checkedId)
    {
    	gender=((RadioButton)findViewById(checkedId)).getText().toString();
    }
    
    class GetAsyncTask extends AsyncTask<String,Integer,String> {
    	
    	Vector<BasicNameValuePair> nameValue=new Vector<BasicNameValuePair>();
		//String...은 개수가 여러개 가변적으로 받아들이고 params에 배열로 저장
		//백그라운드로 동작할 메소드
		//보통시간이 오래걸리는 작업.
    	protected void onPreExecute() {
    		nameValue.add(new BasicNameValuePair("email", email));
			nameValue.add(new BasicNameValuePair("password", password));
			nameValue.add(new BasicNameValuePair("nickname", nickname));
			nameValue.add(new BasicNameValuePair("age", age));
			
			if("남자".equals(gender))
			{
			
				nameValue.add(new BasicNameValuePair("gender", "MALE"));
			}
			else if("여자".equals(gender))
			{
			
				nameValue.add(new BasicNameValuePair("gender", "FEMALE"));
			}
    	}
    	
		protected String doInBackground(String... params){
//			Log.i("getApp","doInBackground");
			
			String result=null;
			try{
				result = sendData(params[0]); 
				
//				Log.i("getApp",result);
	    	}catch (Exception e){
					e.printStackTrace();
			}
			return result;
		}
		//doInBackground메소드가 수행된 결과를 받아들여서 수행된다.
		@Override
		protected void onPostExecute(String result){
			super.onPostExecute(result);
			
//			Log.i("getApp","onPostExecute");
			int index_start= result.indexOf("<join_check>", 0);
			int index_end= result.indexOf("</join_check>", 0);
//			Log.i("getApp","index: "+index_start);
//			Log.i("getApp","index: "+index_end);
			nameValue.clear();
			if(true==(result.substring(index_start, index_end).contains("true")))
			{
				String email= etEmail.getText().toString();
				String password= etPassword.getText().toString();
				Toast.makeText(JoinFormActivity.this, R.string.join_form_join_ok, Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(JoinFormActivity.this, LoginFormActivity.class);
				intent.putExtra("email", email);
				intent.putExtra("password", password);
				startActivity(intent);
			}
			else
			{
				Toast.makeText(JoinFormActivity.this, R.string.join_form_join_notok, Toast.LENGTH_SHORT).show();
			}
			
		}
		
		public String sendData(String url) throws Exception {

			HttpPost request = makeHttpPost(url);

			HttpClient client = new DefaultHttpClient();
			ResponseHandler<String> reshandler = new BasicResponseHandler();
			String result = client.execute(request, reshandler);
			//HttpClient 생성후 execute(HttpPost, ResponseHandler) 메소드를 이용해서 요청 날린다.(return 값은 String Type)
			return result;

		}
	    
		private HttpPost makeHttpPost(String url) throws Exception {
			//HttpPost 인스턴스 생성
			HttpPost request = new HttpPost(url);		//HttpPost 생성시에 생성자로 url을 넣는다
			//후 2번에서 만든 HttpEntity 를 .setEntity 한다.
			request.setEntity(makeEntity(nameValue));
			
			return request;
		}
		//Vector 를 HttpEntity 생성후 넣는다. (2번)
		private HttpEntity makeEntity(Vector<BasicNameValuePair> nameValue) throws Exception {  //BasicNameValuePair 형식(key, value)
			HttpEntity result = null;
			try {
				result = new UrlEncodedFormEntity(nameValue,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			return result;
		}
	}
}
